<template>
  <div class="login-container">
    <div class="login-header">
      <h1 class="login-title">欢迎登录</h1>
    </div>

    <div class="login-form">
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field
            v-model="username"
            name="username"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
            show-password
          />
        </van-cell-group>
        <van-button
          type="primary"
          native-type="submit"
          class="login-btn"
          :loading="loading"
        >
          登录
        </van-button>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { userStore } from "@/store/module/user";
import { showSuccessToast } from "vant";
const router = useRouter();
const useUser = userStore();

const username = ref("");
const password = ref("");
const loading = ref(false);

const onSubmit = async () => {
  if (!username.value || !password.value) return;
  loading.value = true;
  try {
    await useUser.login({ username: username.value, password: password.value });
    await useUser.fetchUser();
    showSuccessToast("登录成功");
    // 路由跳转
    const redirect = router.currentRoute.value?.query?.redirect;
    if (redirect) {
      router.push(decodeURIComponent(redirect));
    } else {
      router.push("/layout/home");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 40px 20px;
  box-sizing: border-box;
  background-color: #f5f5f5;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.login-form {
  flex: 1;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.login-btn {
  margin-top: 20px;
  width: 100%;
}
</style>
